package com.toobigtofail
{
	import realtimelib.Action;
	import realtimelib.P2PGame;

	public class ActionHandler
	{
		private var _p2pGame:P2PGame;
		private var _receiveActionCallback:Function;
		public var groupName:String;
		
		public function ActionHandler(p2pGame:P2PGame, groupName:String, receiveActionCallback:Function=null) {
			_p2pGame = p2pGame;
			_p2pGame.setReceiveObjectCallback(receiveObject);
			this.groupName = groupName;
			if (null != receiveActionCallback)
				_receiveActionCallback = receiveActionCallback;
		}
		
		public function sendAction(type:int, details:*=null):void {
			_p2pGame.sendObject({actionType: type, details:details, group:groupName});
		}
		
		public function receiveObject(peerID:String, object:*):void {
			if (null != object && object.actionType && null != _receiveActionCallback) {
				// make sure the action is coming from your group, otherwise ignore it and remove that user from your christmas card list
				if (object.group && object.group == groupName) {
					_receiveActionCallback.call(this, peerID, new Action(object.actionType, object.details));
				} else {
					_p2pGame.removeUser(peerID);
				}
			}
		}
		
		public function set receiveActionCallback(fn:Function):void { receiveActionCallback = fn; }
	}
}